package com.zzyl.service.customer.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.ReservationConstant;
import com.zzyl.dto.ReservationDto;
import com.zzyl.entity.Elder;
import com.zzyl.entity.Reservation;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ElderMapper;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.mapper.ReservationMapper;
import com.zzyl.service.customer.CustomerReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.NursingProjectVo;
import com.zzyl.vo.ReservationCountVo;
import com.zzyl.vo.ReservationVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class CustomerReservationServiceImpl implements CustomerReservationService {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private ReservationMapper reservationMapper;
    @Autowired
    private ElderMapper elderMapper;

    @Override
    public Integer getCancelledCount() {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 创建一个上午8点的时间对象
        LocalTime amEight = LocalTime.of(8, 0);
        // 创建一个下午6点的时间对象
        LocalTime pmSix = LocalTime.of(18, 0);
        Long memberId = UserThreadLocal.get();
        LocalDateTime startTime = LocalDateTime.of(today, amEight);
        LocalDateTime endTime = LocalDateTime.of(today, pmSix);

        Integer count = reservationMapper.getCountByCreateBy(memberId,startTime,endTime);
        return count;
    }

    @Override
    public List<ReservationCountVo> getCountByTime(Long time) {
        //解析时间戳的日期
        LocalDateTime localDateTime = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = localDateTime.toLocalDate().atStartOfDay();
        LocalDateTime endTime =localDateTime.toLocalDate().atTime(LocalTime.MAX);
        //查询某天已经被预约的每个时段的预约数量
        List<ReservationCountVo> reservationCountVoList  = reservationMapper.getCountByTime(startTime,endTime);
        //组装某天所有时间段的剩余预约数量
        List<ReservationCountVo> allReservationCount =new ArrayList<>();
        LocalTime lowTime = LocalTime.of(8, 0); // 早上8点
        LocalTime highTime = LocalTime.of(18, 0); // 下午6点
        // 循环添加时间节点，从早上8点开始，每半个小时添加一次，直到下午6点
        for (LocalTime i = lowTime; !i.isAfter(highTime); i = i.plus(Duration.ofMinutes(30))) {
            ReservationCountVo reservationCountVo = new ReservationCountVo();
            reservationCountVo.setTime(startTime.with(i));
            reservationCountVo.setCount(ReservationConstant.MAX_RESERVATION_COUNT);//初始化为6
            allReservationCount.add(reservationCountVo);
        }
        // 使用Map来重新组装allReservationCount中的时间段与值
        Map<LocalDateTime, ReservationCountVo> allReservationMap = allReservationCount.stream()
                .collect(Collectors.toMap(ReservationCountVo::getTime, vo -> vo));
        // 遍历已预约时间段列表，更新剩余预约数量
        for (ReservationCountVo reservedVo : reservationCountVoList) {
            ReservationCountVo voToUpdate = allReservationMap.get(reservedVo.getTime());
            if (voToUpdate != null) {
                // 如果找到了对应的时间段，则更新剩余预约数量
                voToUpdate.setCount(Math.max(0, voToUpdate.getCount() - reservedVo.getCount())); // 假设reservedVo.getCount()是已预约的数量
            }
        }
        return allReservationCount;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addReservation(ReservationDto dto) {
        //检查此人是否已经预约过此时间段
        Reservation reservation =reservationMapper.getReservationByMobile(dto);
        if(reservation!=null){
            throw new BaseException(BasicEnum.TIME_ALREADY_RESERVATED_BY_PHONE);
        }
        if(dto.getType()==1){
            //查询家人是否退住
            Elder elder = elderMapper.getElderByName(dto);
            if(elder.getStatus()==5){
                throw new BaseException(BasicEnum.CANNOT_RESERVATION_DUE_ELDER_ALREADY_RETREATED);
            }
        }
        Reservation reservation1 = BeanUtil.copyProperties(dto, Reservation.class);
        reservation1.setStatus(0);
        reservationMapper.addReservation(reservation1);
    }

    @Override
    public PageResponse<ReservationVo> getReservationPage(ReservationDto dto) {
        //获取预约人
        Long memberId = UserThreadLocal.getUserId();//此时获取的是登录用户的id
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        //查询此人的预约列表
        Page<ReservationVo> pageList = reservationMapper.getReservationPage(memberId,dto);
        return PageResponse.of(pageList, ReservationVo.class);
    }

    @Override
    public void cancelReservation(Long id) {
        reservationMapper.cancelReservation(id);
    }
}
